<template>
  <el-dialog title="分配角色" :visible.sync="dialogFormVisible">
    <el-form :model="userData">
      <el-form-item label="" :label-width="formLabelWidth">
        <el-select
          v-model="userData.roleIdList"
          multiple
          placeholder="请选择角色"
        >
          <el-option
            v-for="role in allRoles"
            :key="role.id"
            :label="role.name"
            :value="role.id"
            >{{ role.name }}</el-option
          >
        </el-select>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取 消</el-button>
      <el-button type="primary" @click="onSave">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getUserRoles, allocateUserRole } from "@/api/user";
export default {
  name: "AllocRole",
  data() {
    return {
      dialogFormVisible: false,
      allRoles: [],
      userData: {
        userId: 0,
        roleIdList: [],
      },
      formLabelWidth: "120px",
    };
  },
  methods: {
    //1展示或初始化窗口
    showAndInit(user) {
      this.dialogFormVisible = true;
      //2显示对话框的时候就要显示拥有的角色
      getUserRoles(user.id).then((res) => {
        if (res.data.code === "000000") {
          this.allRoles = res.data.data;
          this.userData.userId = user.id;
          this.userData.roleIdList = res.data.data
            .filter((role) => role.hasPermission)
            .map((role) => role.id);
        }
        console.log("分配角色获取数据", res);
      });
    },
    //2确定-提交方法
    onSave() {
      //点击确定后,对话框关闭
      this.dialogFormVisible = false;
      allocateUserRole(this.userData).then((res) => {
        if (res.data.code === "000000") {
          this.$message.success("给用户分配角色-操作成功!");
        } else {
          this.$message.error("给用户分配角色-操作失败...");
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped></style>
